from rest_framework.response import Response
from rest_framework.views import APIView
from .sers import *
from django.core.paginator import Paginator
from personapp.views import MyTokenAuth
import redis

r = redis.Redis(decode_responses=True)


# 开发 广告接口
class IndexView(APIView):
    def get(self, request):
        # 查询轮播
        queryset_banner = AdvContent.objects.filter(category__key=1).order_by("sort")
        # 查询 快讯
        queryset_kuaixun = AdvContent.objects.filter(category__key=2).order_by("sort")
        # 查看 图片广告
        adv_pic = AdvContent.objects.filter(category__key=3).order_by("sort").first()

        # 展示商品信息
        # 查询所有的一级分类
        queryset = Category.objects.filter(parent_id=None)

        resp = {
            "banner_list": AdvSer(queryset_banner, many=True).data,
            "news_list": AdvSer(queryset_kuaixun, many=True).data,
            "adv_pic": AdvSer(adv_pic).data,
            "category_list": CategoryGoodsSer(queryset, many=True).data
        }

        return Response(resp)


# 专门开发一个 分类接口
class ChannelView(APIView):
    def get(self, request):
        #  查询所有的频道
        queryset_channel = Channel.objects.all()

        ser = ChannelSer(queryset_channel, many=True)

        return Response(ser.data)


#  开发一个商品列表页


class GoodsListView(APIView):

    def get(self, request, cid, flag, num=1):
        if flag == 1:
            queryset = Goods.objects.filter(category3=cid)
        elif flag == 2:
            queryset = Goods.objects.filter(category3=cid).order_by("price")
        elif flag == 3:
            queryset = Goods.objects.filter(category3=cid).order_by("-sale")
        else:
            queryset = Goods.objects.filter(category3=cid)
        # 一页两天记录
        size = 2
        # 分页器实现 分页效果
        # 1、创建一个分页器对象
        p = Paginator(queryset, size)
        # 2、根据页码获取 一页数据
        page_queryset = p.page(num)

        resp = {
            "data": GoodsListSer(page_queryset, many=True).data,
            "total": p.count,  # 总页数
            "size": size,  # 一页大小
        }
        return Response(resp)


# 商品详情接口
class GoodsDetailView(APIView):
    authentication_classes = [MyTokenAuth]

    def get(self, request, pk):




        # 判断是否是登录状态
        user = request.user
        print(type(user))
        collect = False  # 没有收藏
        if user:
            # 判断 商品是否在 商品浏览表中，如果在 则删除  在添加
            GoodsHistory.objects.filter(user_id=user.id, goods_id=pk).delete()
            # 表示用户存在，则 进行 浏览记录添加
            history = GoodsHistory.objects.create(user_id=user.id, goods_id=pk)
            print(history)
            # filter  all exclude         查询集           first()  last() 单个

            # 判断该用户 是否已经收藏该商品  如果存在 true  如果不存在为false
            collect = not r.sismember("collect_" + str(user.id), pk)

        try:
            goods = Goods.objects.get(id=pk)

            # 根据商品 去获取 商品下的 规格属性
            queryset = Specify.objects.filter(goods_id=pk)

            data = {
                "goods_list": GoodsDetailSer(goods).data,
                "specify_list": SpecifySer(queryset, many=True).data
            }

            # 完成用户的浏览记录操作
            r.zincrby("cat_range", 1, goods.id)
            return Response({"msg": "获取成功", "code": 200, "data": data, "collect": collect})
        except Exception as e:
            print(e)
            return Response({"msg": "获取失败", "code": 400})


# 编写片排行接口
class GoodsRangeView(APIView):

    def get(self, request):
        # 先写 浏览排行
        # 取出 redis中记录的排行数据
        g_range = r.zrevrange("cat_range", 0, -1, withscores=True)
        print(g_range)
        goods_list = []
        score_list = []
        for gid, score in g_range:
            goods = Goods.objects.get(id=gid)
            goods_list.append(GoodsListSer(goods).data)
            score_list.append(score)
        return Response({"goods_list": goods_list, "score_list": score_list})
